package com.tongcao.cn.aspect;

import com.tongcao.cn.annotation.SysLog;
import com.tongcao.cn.domain.model.SysLogEntity;
import com.tongcao.cn.mapper.SysLogEntityMapper;
import com.tongcao.cn.util.FastJsonUtils;
import com.tongcao.cn.util.HttpContextUtils;
import com.tongcao.cn.util.IPUtils;
import com.tongcao.cn.util.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;

/**
 * @Author:tongcao
 * @Date:2018/8/28 17:24
 * Description:记录系统时间切面
 */
@Aspect
@Component
@Slf4j
public class SysLogAspect {

//    @Autowired
//    SysLogEntityMapper sysLogEntityMapper;

    @Pointcut("@annotation(com.tongcao.cn.annotation.SysLog)")
    public Object logPointCut(ProceedingJoinPoint pjp) throws Throwable {
        return around(pjp);
    }


    public Object around(ProceedingJoinPoint point) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        point.proceed();
        stopWatch.stop();
        long millis = stopWatch.getTotalTimeMillis();
        //持久化db
        saveSysLog(point, millis);
        return point;
    }

    private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        SysLogEntity sysLog = new SysLogEntity();
        SysLog syslog = method.getAnnotation(SysLog.class);
        if (syslog != null) {
            //注解上的描述
            sysLog.setOperation(syslog.value());
        }

        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");

        //请求的参数
        Object[] args = joinPoint.getArgs();
//        try {
//            String params = Convert.asString(args[0]);
//            sysLog.setParams(params);
//        } catch (Exception e) {
//
//        }

        //获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        Map<String, Object> parameterMap = RequestUtils.getParameterMap(request);
        sysLog.setParams(FastJsonUtils.convMapToJSON(parameterMap));
        //设置IP地址
        sysLog.setIp(IPUtils.getIpAddr(request));

        //用户名
        String username = "胡羽-->tongcao";
        sysLog.setUsername(username);

        sysLog.setTime(time);
        sysLog.setCreateDate(new Date());
        //保存系统日志
//        sysLogEntityMapper.insert(sysLog);
    }
}
